<?php

namespace app\business\controller;

use app\business\model\BusinessClassify;
use app\business\model\BusinessLogin;
use app\business\model\BusinessMenu;
use app\business\model\BusinessOrder;
use think\Controller;
use app\business\controller\Base;
use think\Session;
use think\Db;

class Order extends Base
{

    public $url = 'newopen.imdada.cn/api';
        // url参数
    public  $cityurl =      '/cityCode/list';
    public  $addorderurl =  '/order/addOrder';



  //取消原因接口地址
    protected $qxyyurl = 'newopen.qa.imdada.cn/api/order/cancel/reasons';
    protected $qxorderurl = 'newopen.qa.imdada.cn/api/order/formalCancel';


    public function index()
    {

        $username = Session::get('username');

        $count = BusinessLogin::where('username', $username)->find();

        $num = $count['business_id']; //这个是当前商家

        $demo = BusinessOrder::where('shop_id', $num);

        $data = Db::table('business_order')
            ->join('business_info',['business_order.shop_id=business_info.business_id'],'left')
            ->join('business_lessen',['business_order.shop_id=business_lessen.business_id','business_order.lessen_id=business_lessen.id'],'left')
            ->where('business_order.shop_id',$num)
            ->where('business_order.static',2)
            ->select();

        $this->assign('data', $data);

        return $this->fetch();
    }

    public function order_detail($order_num)
    {


        $order = db('order')->where('order_num',$order_num)->find();

        $order_goods = db('order_goods')->where('oid',$order['id'])->select();

        $this->assign('data',$order_goods);

        return $this->fetch();

    }

    public function delete($id)
    {
        $state = db('business_abroad_order')->where('id' .'='. $id)->delete();
        if ($state) {
            $this->redirect('business/order/index');
        }else{
            $this->error('错误','business/order/index');
        }
    }

    public function update($id)
    {
        $data = db('business_abroad_order')->where('id',$id)->find();

        switch ($data['static']) {
            case 2:
                $arr['static'] = 3;

                break;
            case 3:
                $arr['static'] = 4;
                break;
        }

        $arr['id'] = $id;
        db('business_abroad_order')->update($arr);
        return $this->redirect('business/order/index');
    }

    public function search()
    {

        $shop_id = session::get('uid');//商家ID
        $search = input('post.search');
        $data = Db::table('business_abroad_order')
            ->Field('a.id as aid,a.post_time as shangchuan,a.*,c.*,i.*')
            ->alias('a')
            ->join('business_collect c','a.collect_id = c.id' ,'LEFT')
            ->join('business_info i' ,'a.shop_id = i.id')
            ->where('c.addressee','like','%'.$search.'%')
            ->where('a.shop_id','=',"$shop_id")

            ->order('a.id desc')

            ->paginate(10);

        $page = $data->render();

        $this->assign('page',$page);

        $this->assign('data',$data);

        return $this->fetch('index');
    }

    public function internal()
    {

        $username = Session::get('username');

        $count = BusinessLogin::where('username', $username)->find();

        $num = $count['business_id']; //这个是当前商家

        $demo = BusinessOrder::where('shop_id', $num);

        $data = Db::table('business_order')
            ->join('business_info',['business_order.shop_id=business_info.business_id'],'left')
            ->join('business_lessen',['business_order.lessen_id=business_lessen.id'],'left')
            ->where('shop_id',$num)
            ->where('static',1)
            ->select();
		
		//var_dump( $data);
		//echo DB::table('business_order')->getlastsql();
        $this->assign('data', $data);

        return $this->fetch();
    }

    public function add_internal()
    {
        $data = Db::table('business_table_classify')
            ->Field('t.id as tid,tc.*,t.*')
            ->alias('tc')
            ->join('business_table t','tc.classify_name = t.table_classify')
            ->order('t.id desc')
            ->select();


        $this->assign('data',$data);

        return $this->fetch();

    }

    public function do_add_internal()
    {
        $shop_id = session::get('uid');//商家ID
        $data = input('post.');

        $table_id = input('post.table_id');
        $data1 = db('business_table')->where('id',$table_id)->find();

        $data['ty_name'] = $data1['table_classify'];
        $data['post_time'] = date('Y-m-d H:i:s');
        $data['number'] = strtotime(date('Y-m-d H:i:s',time()));
        $data['shop_id'] = $shop_id;



        db('business_internal_order')->insert($data);

        return $this->redirect('business/order/internal');
    }

    public function internal_update($id)
    {
        $data = db('business_internal_order')->where('id',$id)->find();

        switch ($data['static']) {
            case 1:
                $arr['static'] = 2;

                break;
            case 2:
                $arr['static'] = 1;

                break;
        }
        $arr['id'] = $id;
        db('business_internal_order')->update($arr);
        return $this->redirect('business/order/internal');
    }

    public function internal_delete($id)
    {
        $state = db('business_internal_order')->where('id' .'='. $id)->delete();
        if ($state) {
            $this->redirect('business/order/internal');
        }else{
            $this->error('错误','business/order/internal');
        }
    }

    public function yuyue()
    {

        //var_dump($_SESSION);die;
        $data = db('yuyue')->where('shopid',session::get('business_id'))->select();

        $this->assign('data',$data);

        return $this->fetch();
    }

    public function yuyue_update($id,$static)
    {
       $data['id'] = $id;

       $data['static'] = $static;
        db('yuyue')->update($data);
       $this->fsmb($id,$static);

        return $this->success('成功！');
    }
    //发送模板消息
    public function fsmb($id,$static)
    {
         $yuyue = db('yuyue')->find($id);
         $agent = db('setting')->where('agent_id',$yuyue['agent_id'])->find();

        $content['appid'] = $agent['appid'];
        $content['appsecret'] = $agent['appsecret'];
        $content['form_id'] = $yuyue['form_id'];
        $content['time'] = date('Y-m-d H:i:s');

        $content['openid'] = $yuyue['openid'];
            if ($static == 3) {
                $type = 1;
                $content['yycg_id'] = $agent['yycg_id'];
                $content['quyu'] = $yuyue['quyu'];
                $content['yyname'] = $yuyue['name'];
                $content['yytel'] = $yuyue['tel'];
                $content['yytime'] = $yuyue['ymd'].' '.$yuyue['time'];
                $content['tishi'] = '取消预约请至少提前半天。';
                $content['dangqiantime'] = date('Y-m-d');



            } else if($static == 2){

                $info = db('info')->find($yuyue['shopid']);

                $type = 2;
                $content['yysb_id'] = $agent['yysb_id'];
                $content['xdtime'] = $yuyue['posttime'];
                $content['jujue'] = $yuyue['jujue'];
                $content['dianming'] = $info['business_name'];





            }
        $a = send_notice_pay($content,$type);

        //var_dump($a);die;

    }


    public function yuyue_do_update()
    {
        $data = input('post.');
        if (empty($data['jujue'])) {
            return $this->error('请填写缘由！');
        }
        //var_dump($data);die;
        db('yuyue')->update($data);
        $this->fsmb($data['id'],$data['static']);

         return $this->success('成功！');
    }



    public  function yuyue_delete($id)
    {
        db('yuyue')->delete($id);

        return $this->success('成功！');
    }


    //商家接订单
    public function jiedan($order_num) // 此处ID 为 订单号码
    {



         //订单详情
        $order = db('order')->where('order_num',$order_num)->find();
        //判断是否为外卖订单
        if ($order['static'] == 2) {
            # code...


        //进行达达操作
        //获取商家详情
        $shopdata = db('info')->find($order['shop_id']);
        $setting = db('setting')->find($shopdata['agent_id']);
        //判断商家是否开启达达
        if ($shopdata['dada'] == 1) {

             $dadadata = array(
        'shop_no'=>  $shopdata['shop_bian'],//门店编号
        'origin_id'=> $order_num,//订单id

        'tips'=> 0,//小费
        'cargo_price'=> $order['allPayMoney'],
        // 'cargo_num'=> 2,
        'is_prepay'=> 0,
        'expected_fetch_time'=>time()+600,
        'receiver_name'=> $shopdata['business_name'],
        'receiver_address'=> $shopdata['business_address'],
        'receiver_lat'=> $order['user_lat'],
        'receiver_lng'=> $order['user_lng'],
        'receiver_phone'=> $order['order_tel'],
        'callback'=>'https://app.yizhizaibo.cn/eat/business/order/dadahuidiao'
        //'callback'=>'http://newopen.imdada.cn/inner/api/order/status/notify'
    );

        $arr = json_decode(rtrim(str_replace("renderReverse&&renderReverse(","",httpGet('http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location='.$order['user_lat'].','.$order['user_lng'].'&output=json&pois=1&ak=A2vHtcav1E7fgqO1iiFWuPWt')), ')'),true);
        $city = $arr['result']['addressComponent']['city'];

         $data = array(
                'app_key' => $setting['dada_key'],
                'format' => 'json',
                'body' =>'',

                'source_id'=> $shopdata['zhanghu_id'],

                'v' => '1.0',

                );

        $dadadata['city_code'] = $this->shujv($setting['dada_secret'],$data,$city);

        if (empty($dadadata['city_code'])) {
            return $this->error('该地区不支持达达配送！');die;
        }
        $dadadata = json_encode($dadadata);

        $requestParams = array();
        $requestParams['app_key'] = $setting['dada_key'];
        $requestParams['body'] = $dadadata;
        $requestParams['format'] = 'json';
        $requestParams['v'] = '1.0';
        $requestParams['source_id'] = $shopdata['zhanghu_id'];
        $requestParams['timestamp'] = time();

        $requestParams['signature'] = $this->paixu($requestParams,$setting['dada_secret']);

        $dadadata = $this->post($requestParams,$this->url.$this->addorderurl);

        //var_dump($dadadata);die;
    }

        }

        $orderwhere['id'] = $order['id'];
        $orderwhere['is_comment'] = 1;

        db('order')->update($orderwhere);

        return $this->success('接单成功！');

    }

        protected function shujv($app_secret,$data,$city){ //参数1 app_secret   参数2



            $data['timestamp'] = time();
           $data['signature'] = $this->paixu($data,$app_secret);

          $data = $this->post($data,$this->url.$this->cityurl);
 //var_dump($data);die;
          $city = $this->city($data,$city);

          return $city;

        }

        protected function paixu($data,$app_secret){
        //1.升序排序
        ksort($data);
        //2.字符串拼接
        $args = "";
        foreach ($data as $key => $value) {
            $args.=$key.$value;
        }
        $args = $app_secret.$args.$app_secret;

        //3.MD5签名,转为大写
       // $data['signature'] = strtoupper(md5($args));

        return strtoupper(md5($args));

        }
        protected function post($data,$postUrl)
        {
            $data = json_encode($data);



        $curlPost = $data;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-type: application/json"));
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        //var_dump($data);die;
        curl_close($ch);

        return $data;
        }
        protected function city($data,$cityname){

        $data = $this->chuli($data);



          foreach ($data as $key => $value) {
                // var_dump($value->cityName);
                // var_dump($value->cityCode);die;
                $dadacityname = $value->cityName.'市';
                // 判断达达配送地区是否有当前城市
            if ($dadacityname == $cityname) {


                return $value->cityCode;
            }
          }

        }
          public function chuli($data)
          {


                //处理返回结果
                //去除末尾
                $data =  substr_replace($data,"",-25);
                //去除开头
                $data = substr($data,29);
                //转化json
              $data = json_decode($data);

              //转化数组


              return (array)$data;
          }
    //达达接口回调地址
    public function dadahuidiao()
    {


        // 订单状态(待接单＝1 待取货＝2 配送中＝3 已完成＝4 已取消＝5 已过期＝7 指派单=8 妥投异常之物品返回中=9 妥投异常之物品返回完成=10 创建达达运单失败=1000 可参考文末的状态说明）

        $data = input('post.');

        $data = json_encode($data);
//file_put_contents('go_pdm_log.txt', $data, FILE_APPEND);
        $data = json_decode($data);


        //订单号
        $order_num = $data->order_id;

        //订单状态
        $is_comment = $data->order_status;

        //获取订单详情
        $order = db('order')->where('order_num',$order_num)->find();

        if ($order['is_comment'] !== $is_comment) {
            # code...
        }

        $where['id'] = $order['id'];
        if ($is_comment == 3) {
        $where['is_comment'] = 2;
        }elseif($is_comment == 4){
        $where['is_comment'] = 3;
        }else{
            $where['is_comment'] = 2;
        }

        $static = db('order')->update($where);
        if ($static) {
            return 'SUCCESS';
        }


    }


    public function tixing()
    {
        $data = db('tixing')->where('id',1)->find();



        $update = array(
            'value' => 0,
            'id' => 1
            );

        db('tixing')->update($update);
        return $data['value'];
    }


}